package com.freightoa.sgl_login.presentation.screen

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.freightoa.foundation.viewmodel.BaseState
import com.freightoa.foundation.viewmodel.BaseViewModel
import com.freightoa.foundation.viewmodel.UiIntent
import com.freightoa.sgl_login.domain.LoginUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

// 登录状态
sealed interface LoginState : BaseState {
    data object Idle : LoginState
    data object Loading : LoginState
    data class Success(val message: String) : LoginState
    data class Error(val errorMessage: String) : LoginState
}

// 登录意图
sealed interface LoginIntent : UiIntent {
    data class Login(val username: String, val password: String) : LoginIntent
    data object Idle : LoginIntent
}

@HiltViewModel
class LoginViewModel @Inject constructor(private val loginUseCase: LoginUseCase) : BaseViewModel<LoginState, LoginIntent>() {

    private val _uiStateFlow = MutableStateFlow<LoginState>(LoginState.Idle)
    override val uiState: Flow<LoginState> = _uiStateFlow.asStateFlow()

    override fun handleIntent(intent: LoginIntent) {
        viewModelScope.launch {
            when (intent) {
                is LoginIntent.Login -> {
                    _uiStateFlow.value = LoginState.Loading
                    val result = loginUseCase(intent.username, intent.password)
                    if (result.isSuccess) {
                        _uiStateFlow.value = LoginState.Success("登录成功")
                    } else {
                        _uiStateFlow.value = LoginState.Error(result.exceptionOrNull()?.message?:"Login Failed")
                    }
                }
                is LoginIntent.Idle->{
                    _uiStateFlow.value=LoginState.Idle
                }
            }
        }
    }
}